/**********************************************************************
 * Copyright: (C)2024 LingYun IoT System Studio
 * Author: LiJiahui<2199250859@qq.com>
 *
 * Description: NTP client for ESP8266 using modular UART communication.
 *
 * ChangeLog:
 * Version    Date       Author            Description
 * V1.0.0  2025.07.5    LiJiahui      Release initial version
 * V1.1.0  2025.07.26   LiJiahui      Integrated with new uart_comm module for bare-metal
 * V3.0.0  2025.08.07   LiJiahui      Adapted to new uart_comm struct encapsulation
 * V3.0.1  2025.08.08   LiJiahui      Fixed bug of printing binary NTP packet
 *
 ***********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "uart_comm.h"

#include "ntp_client.h"
#include "usart.h"
#include "main.h"

static wifi_status_t wifi_status = WIFI_DISCONNECTED;

//UART 句柄
extern UART_HandleTypeDef huart2;

static ntp_error_t esp8266_connect_wifi(const char *ssid, const char *password);
static ntp_error_t esp8266_create_udp_connection(const char *server,
		uint16_t port);
static ntp_error_t esp8266_send_ntp_packet(void);
static void ntp_packet_to_time(const ntp_packet_t *packet, rtc_time_t *time);
static uint64_t ntp_timestamp_to_unix(uint64_t ntp_timestamp);
static void unix_timestamp_to_rtc_time(uint64_t unix_timestamp,
		rtc_time_t *time);

// NTP 客户端初始化
ntp_error_t ntp_init(void)
{
	ntp_printf("Initializing NTP client...\r\n");

	if (esp8266_send_command("AT\r\n", ESP8266_RESPONSE_OK, 1000)
			!= NTP_SUCCESS)
	{
		ntp_printf("ESP8266 not responding\r\n");
		return NTP_ERROR_WIFI_CONNECT;
	}

	if (esp8266_send_command("AT+CWMODE=1\r\n", ESP8266_RESPONSE_OK, 2000)
			!= NTP_SUCCESS)
	{
		ntp_printf("Failed to set WiFi mode\r\n");
		return NTP_ERROR_WIFI_CONNECT;
	}

	if (esp8266_send_command("AT+CIPMUX=1\r\n", ESP8266_RESPONSE_OK, 2000)
			!= NTP_SUCCESS)
	{
		ntp_printf("Failed to enable multiple connection\r\n");
		return NTP_ERROR_WIFI_CONNECT;
	}

	ntp_printf("NTP client initialized successfully\r\n");
	return NTP_SUCCESS;
}

// 连接到指定的 WiFi 网络
ntp_error_t ntp_wifi_connect(const char *ssid, const char *password)
{
	ntp_error_t result;

	if (!ssid || !password)
	{
		return NTP_ERROR_INVALID_PARAM;
	}

	ntp_printf("Connecting to WiFi :%s\r\n", ssid);

	wifi_status = WIFI_CONNECTING;

	result = esp8266_connect_wifi(ssid, password);

	if (result == NTP_SUCCESS)
	{
		wifi_status = WIFI_CONNECTED;
		ntp_printf("WIFI connected successfully\r\n");
	}
	else
	{
		wifi_status = WIFI_ERROR;
		ntp_printf("WIFI connection failed\r\n");
	}

	return result;
}

// 获取当前的 WiFi 连接状态
wifi_status_t ntp_get_wifi_status(void)
{
	return wifi_status;
}

// 从 NTP 服务器获取网络时间
ntp_error_t ntp_get_time(rtc_time_t *time)
{
	const char *ntp_servers[] =
	{ NTP_SERVER_PRIMARY, NTP_SERVER_SECONDARY, NTP_SERVER_TERTIARY };
	ntp_packet_t ntp_packet;
	ntp_error_t result = NTP_ERROR_RECEIVE_TIMEOUT;
	int i;

	if (!time)
	{
		return NTP_ERROR_INVALID_PARAM;
	}

	if (wifi_status != WIFI_CONNECTED)
	{
		ntp_printf("wifi not connected\r\n");
		return NTP_ERROR_WIFI_CONNECT;
	}

	ntp_printf("Getting time from NTP server...\r\n");

	for (i = 0; i < 3; i++)
	{
		ntp_printf("Trying NTP server:%s\r\n", ntp_servers[i]);

		if (esp8266_create_udp_connection(ntp_servers[i], 123) != NTP_SUCCESS)
		{
			ntp_printf("Failed to create UDP connection to %s\r\n",
					ntp_servers[i]);
			continue;
		}

		if (esp8266_send_ntp_packet() != NTP_SUCCESS)
		{
			ntp_printf("Failed to send NTP packet\r\n");
			// 确保关闭连接，即使发送失败
			esp8266_send_command("AT+CIPCLOSE=0\r\n", ESP8266_RESPONSE_OK,
					1000);
			continue;
		}

		if (esp8266_receive_ntp_response(&ntp_packet) == NTP_SUCCESS)
		{
			ntp_printf("NTP response received from %s\r\n", ntp_servers[i]);
			result = NTP_SUCCESS;
			// 收到响应后关闭连接
			esp8266_send_command("AT+CIPCLOSE=0\r\n", ESP8266_RESPONSE_OK,
					1000);
			break;
		}

		// 如果没有收到响应，也要关闭连接再尝试下一个服务器
		esp8266_send_command("AT+CIPCLOSE=0\r\n", ESP8266_RESPONSE_OK, 1000);
		udelay(1000); // 避免连续尝试过快
	}

	if (result != NTP_SUCCESS)
	{
		ntp_printf("Failed to get time from all NTP servers\r\n");
		return result;
	}

	ntp_packet_to_time(&ntp_packet, time);
	ntp_printf("Time obtained:%04d-%02d-%02d %02d:%02d:%02d\r\n", time->tm_year,
			time->tm_mon, time->tm_mday, time->tm_hour, time->tm_min,
			time->tm_sec);

	return NTP_SUCCESS;
}

// 同步 RTC 时间，将网络时间写入 RTC 芯片
ntp_error_t ntp_sync_rtc(void)
{
	extern i2c_bus_t i2c_bus[]; // 确保 i2c_bus 被正确声明和初始化
	rtc_time_t netword_time;

	ntp_error_t result = ntp_get_time(&netword_time);
	if (result != NTP_SUCCESS)
		return result;

	if (i2c_bus[ISL1208_I2CBUS].addr == 0x00) // 检查是否已初始化，如果0x00是未初始化的标志
	{
		printf("Initializing I2C bus %d with address 0x%02X\r\n",
				ISL1208_I2CBUS, ISL1208_CHIPADDR);
		if (i2c_init(ISL1208_I2CBUS, ISL1208_CHIPADDR) != 0)
		{
			printf("I2C initialization failed\r\n");
			return NTP_ERROR_RTC_SYNC;
		}
	}

	if (set_rtc_time(netword_time) != 0)
	{
		printf("Failed to sync RTC time\r\n");
		// 即使失败，也尝试释放I2C资源
		i2c_term(ISL1208_I2CBUS);
		return NTP_ERROR_RTC_SYNC;
	}

	printf("Releasing I2C bus %d\r\n", ISL1208_I2CBUS);
	i2c_term(ISL1208_I2CBUS);

	printf("RTC synchronized successfully\r\n");
	return NTP_SUCCESS;
}



ntp_error_t esp8266_send_command(const char *cmd, const char *expected_response, uint32_t timeout_ms)
{
	// 标记我们是否特别在等待 CIPSEND 的 '>' 提示符
	bool waiting_for_cipsend_prompt = (expected_response != NULL
			&& strcmp(expected_response, ">") == 0);

	// 在发送命令前，清空之前的解析结果标志和数据
	enter_critical_section();// 保护共享变量
	uart_comm_data.at_response_ready = false;
	memset(uart_comm_data.parsed_at_response, 0,
			sizeof(uart_comm_data.parsed_at_response));
	uart_comm_data.parsed_at_response_len = 0;
	exit_critical_section();

	// 如果 cmd 不为空，则发送命令
	if (cmd && strlen(cmd) > 0)
	{
		//ntp_printf("Sending AT command: %s", cmd); // cmd 应该以 \r\n 结尾
		// 发送 AT 命令
		if (HAL_UART_Transmit(&huart2, (uint8_t*) cmd, strlen(cmd),
				HAL_MAX_DELAY) != HAL_OK) // 使用 HAL_MAX_DELAY 等待发送完成
		{
			ntp_printf("HAL_UART_Transmit failed for command: %s\r\n", cmd);
			return NTP_ERROR_SEND_PACKET;
		}
	}
	else
	{
		ntp_printf("Waiting for response: %s\r\n", expected_response);
	}




	uint32_t start_time = HAL_GetTick();

	// 轮询等待响应
	while ((HAL_GetTick() - start_time) < timeout_ms)
	{
		// 核心：在等待期间，周期性地调用数据解析函数
		uart_process_received_data();

		enter_critical_section(); // 保护对 uart_comm_data.at_response_ready 和 uart_comm_data.parsed_at_response 的读取
		if (uart_comm_data.at_response_ready)
		{
			char temp_response[PARSED_DATA_BUFFER_SIZE];
			strncpy(temp_response, uart_comm_data.parsed_at_response,
					PARSED_DATA_BUFFER_SIZE - 1);
			temp_response[PARSED_DATA_BUFFER_SIZE - 1] = '\0';

			// 重要的：消费掉当前的 uart_comm_data.at_response_ready 标志
			uart_comm_data.at_response_ready = false;
			exit_critical_section(); // 尽快退出临界区

			// 1. 检查是否收到了预期响应
			if (strstr(temp_response, expected_response) != NULL)
			{
				ntp_printf("Received expected response: %s\r\n",
						expected_response);
				return NTP_SUCCESS;
			}

			// 2. 检查错误/失败响应
			if (strstr(temp_response, "ERROR") != NULL
					|| strstr(temp_response, "FAIL") != NULL)
			{
				ntp_printf("Error/Fail response received: %s\r\n",
						temp_response);
				return NTP_ERROR_WIFI_CONNECT; // 或者更具体的错误码
			}

			// 3. 特殊处理：如果当前是在等待 CIPSEND 的 '>'，并且收到了 OK
			if (waiting_for_cipsend_prompt
					&& strstr(temp_response, "OK") != NULL)
			{
				ntp_printf(
						"Received OK (preceding '>'). Continuing to wait for '>'.\r\n");
			}

			// 4. 新增：忽略 +IPD 这类非预期响应
			if (strstr(temp_response, "+IPD") != NULL)
			{
				ntp_printf(
						"Received +IPD, but not waiting for it. Ignoring...\r\n");
			}
			else
			{
				// 如果是其他非预期的响应
				ntp_printf(
						"Received unhandled response: %s (while waiting for: %s)\r\n",
						temp_response, expected_response);
			}
		}
		else
		{
			exit_critical_section(); // 如果没有 uart_comm_data.at_response_ready，确保退出临界区
		}

		taskYIELD();
	}

	ntp_printf("Response timeout for command: %s (waiting for %s)\r\n",
			cmd ? cmd : "NO COMMAND SENT", expected_response);
	return NTP_ERROR_RECEIVE_TIMEOUT;
}

// 连接 WiFi 网络
static ntp_error_t esp8266_connect_wifi(const char *ssid, const char *password)
{
	char cmd[128];

	// 先尝试断开当前连接
	esp8266_send_command("AT+CWQAP\r\n", ESP8266_RESPONSE_OK, 2000); // 不关心结果，继续连接

	snprintf(cmd, sizeof(cmd), "AT+CWJAP=\"%s\",\"%s\"\r\n", ssid, password);

	return esp8266_send_command(cmd, ESP8266_RESPONSE_OK, 15000); // 增加超时时间，WiFi连接可能较慢
}

// 创建 UDP 连接
static ntp_error_t esp8266_create_udp_connection(const char *server,
		uint16_t port)
{
	char cmd[128];

	snprintf(cmd, sizeof(cmd), "AT+CIPSTART=0,\"UDP\",\"%s\",%d\r\n", server,
			port);
	return esp8266_send_command(cmd, ESP8266_RESPONSE_OK, 5000);
}

// 发送 NTP 请求包
static ntp_error_t esp8266_send_ntp_packet(void)
{
	uint8_t ntp_packet_data[NTP_PACKET_SIZE] =
	{ 0 }; // 确保是 uint8_t 数组
	char cmd[64];

	ntp_packet_data[0] = 0x1B; // NTP协议版本和模式

	snprintf(cmd, sizeof(cmd), "AT+CIPSEND=0,%d\r\n", NTP_PACKET_SIZE);

	// 等待 ">" 提示符
	if (esp8266_send_command(cmd, ">", 2000) != NTP_SUCCESS)
	{
		return NTP_ERROR_SEND_PACKET;
	}

	// 发送 NTP 数据包
	if (HAL_UART_Transmit(&huart2, ntp_packet_data, NTP_PACKET_SIZE,
			HAL_MAX_DELAY) != HAL_OK)
	{
		ntp_printf("Failed to transmit NTP packet\r\n");
		return NTP_ERROR_SEND_PACKET;
	}

	ntp_printf("NTP packet transmitted. Waiting for SEND OK...\r\n");

	// 等待 "SEND OK" 响应
	uint32_t start_time = HAL_GetTick();
	while ((HAL_GetTick() - start_time) < 5000)
	{ // 等待5秒钟
		uart_process_received_data(); // 持续处理接收到的数据

		enter_critical_section();
		if (uart_comm_data.at_response_ready)
		{
			char temp_response[PARSED_DATA_BUFFER_SIZE];
			strncpy(temp_response, uart_comm_data.parsed_at_response,
					PARSED_DATA_BUFFER_SIZE - 1);
			temp_response[PARSED_DATA_BUFFER_SIZE - 1] = '\0';
			uart_comm_data.at_response_ready = false; // 消费掉标志
			exit_critical_section();

			if (strstr(temp_response, "SEND OK") != NULL)
			{
				ntp_printf("SEND OK received.\r\n");
				return NTP_SUCCESS;
			}
			if (strstr(temp_response, "ERROR") != NULL
					|| strstr(temp_response, "FAIL") != NULL)
			{
				ntp_printf("SEND ERROR received: %s\r\n", temp_response);
				return NTP_ERROR_SEND_PACKET;
			}

			// 忽略 +IPD，让 receive 函数去处理
			if (strstr(temp_response, "+IPD") != NULL)
			{
				ntp_printf("Received +IPD, ignoring...\r\n");
			}
		}
		else
		{
			exit_critical_section(); // 如果没有标志，也要释放锁
		}
		taskYIELD(); // 建议使用 taskYIELD() 让出 CPU，避免忙等
	}

	ntp_printf("SEND OK timeout\r\n");
	return NTP_ERROR_SEND_PACKET;
}

ntp_error_t esp8266_receive_ntp_response(ntp_packet_t *packet)
{
	uint32_t start_time = HAL_GetTick();

	while ((HAL_GetTick() - start_time) < NTP_TIMEOUT_MS)
	{
		// 调用通用解析器来处理接收到的所有数据
		uart_process_received_data();

		enter_critical_section();
		// 检查通用解析器是否已经准备好了 IPD 数据
		if (uart_comm_data.received_ipd_data_ready
				&& uart_comm_data.received_ipd_data_len == NTP_PACKET_SIZE)
		{
			// 如果 IPD 数据已准备好，且长度正确，则复制数据
			// 填充 NTP packet 结构体 (注意字节序转换)
			packet->li_vn_mode = uart_comm_data.received_ipd_data_buffer[0];
			packet->stratum = uart_comm_data.received_ipd_data_buffer[1];
			packet->poll = uart_comm_data.received_ipd_data_buffer[2];
			packet->precision = uart_comm_data.received_ipd_data_buffer[3];

			packet->root_delay =
					(uint32_t) uart_comm_data.received_ipd_data_buffer[4] << 24
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[5]
									<< 16
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[6]
									<< 8
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[7]
									<< 0;
			packet->root_dispersion =
					(uint32_t) uart_comm_data.received_ipd_data_buffer[8] << 24
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[9]
									<< 16
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[10]
									<< 8
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[11]
									<< 0;
			packet->ref_id =
					(uint32_t) uart_comm_data.received_ipd_data_buffer[12] << 24
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[13]
									<< 16
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[14]
									<< 8
							| (uint32_t) uart_comm_data.received_ipd_data_buffer[15]
									<< 0;

			packet->ref_timestamp =
					(uint64_t) uart_comm_data.received_ipd_data_buffer[16] << 56
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[17]
									<< 48
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[18]
									<< 40
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[19]
									<< 32
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[20]
									<< 24
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[21]
									<< 16
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[22]
									<< 8
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[23]
									<< 0;
			packet->orig_timestamp =
					(uint64_t) uart_comm_data.received_ipd_data_buffer[24] << 56
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[25]
									<< 48
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[26]
									<< 40
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[27]
									<< 32
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[28]
									<< 24
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[29]
									<< 16
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[30]
									<< 8
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[31]
									<< 0;
			packet->recv_timestamp =
					(uint64_t) uart_comm_data.received_ipd_data_buffer[32] << 56
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[33]
									<< 48
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[34]
									<< 40
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[35]
									<< 32
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[36]
									<< 24
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[37]
									<< 16
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[38]
									<< 8
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[39]
									<< 0;
			packet->trans_timestamp =
					(uint64_t) uart_comm_data.received_ipd_data_buffer[40] << 56
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[41]
									<< 48
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[42]
									<< 40
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[43]
									<< 32
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[44]
									<< 24
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[45]
									<< 16
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[46]
									<< 8
							| (uint64_t) uart_comm_data.received_ipd_data_buffer[47]
									<< 0;

			// 重置 IPD 数据的标志和缓冲区
			uart_comm_data.received_ipd_data_ready = false;
			uart_comm_data.received_ipd_data_len = 0;
			exit_critical_section();
			return NTP_SUCCESS;
		}
		else
		{
			exit_critical_section();
		}
		taskYIELD(); // 建议使用 taskYIELD() 让出 CPU，避免忙等
	}

	// 超时
	ntp_printf("[NTP] NTP receive timeout. No expected NTP IPD received.\r\n");
	return NTP_ERROR_RECEIVE_TIMEOUT;
}

// 将收到的 NTP 数据包解析为日历时间
static void ntp_packet_to_time(const ntp_packet_t *packet, rtc_time_t *time)
{
	uint64_t ntp_timestamp = packet->trans_timestamp;
	uint64_t unix_timestamp = ntp_timestamp_to_unix(ntp_timestamp);

	unix_timestamp += (TIME_ZONE_OFFSET * 3600); // 添加时区偏移
	unix_timestamp_to_rtc_time(unix_timestamp, time);
}

// 将 NTP 时间戳转换为 UNIX 时间戳
static uint64_t ntp_timestamp_to_unix(uint64_t ntp_timestamp)
{
	// NTP 时间戳是64位，高32位是整数秒，低32位是小数秒
	uint32_t seconds = (uint32_t) (ntp_timestamp >> 32);
	return (uint64_t) (seconds - NTP_EPOCH_OFFSET);
}

// 将 UNIX 时间戳转换为 rtc_time_t 日历结构
static void unix_timestamp_to_rtc_time(uint64_t unix_timestamp,
		rtc_time_t *time)
{
	uint32_t year = 1970;
	uint32_t days_in_year;
	uint32_t days_in_month[] =
	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	uint32_t month = 1;
	uint32_t total_days;

	uint32_t days = unix_timestamp / 86400; // 总天数
	uint32_t seconds_in_day = unix_timestamp % 86400; // 一天中的秒数

	time->tm_hour = seconds_in_day / 3600;
	time->tm_min = (seconds_in_day % 3600) / 60;
	time->tm_sec = seconds_in_day % 60;

	// 计算年份
	while (days
			>= (days_in_year =
					((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ?
							366 : 365))
	{
		days -= days_in_year;
		year++;
	}
	time->tm_year = year;

	// 处理闰年2月
	if (((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
	{
		days_in_month[1] = 29;
	}

	// 计算月份和日期
	while (days >= days_in_month[month - 1])
	{
		days -= days_in_month[month - 1];
		month++;
	}
	time->tm_mon = month; // 月份从1开始
	time->tm_mday = days + 1; // 日期从1开始

	// 计算星期 (1970年1月1日是星期四，所以加4)
	total_days = (unix_timestamp / 86400) + 4;
	time->tm_wday = total_days % 7; // 0=Sunday, 1=Monday...
}

/* ----------------------------------- Functions used in FreeRTOS --------------------------- */

//获取事时间
int32_t ntp_sync_and_get_time_with_lock(SemaphoreHandle_t xMutex,
		rtc_time_t *current_time)
{

	if (xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE)
	{
		// 执行NTP同步
		if (ntp_sync_rtc() != NTP_SUCCESS)
		{
			printf("NTP sync failed\r\n");
			xSemaphoreGive(xMutex); // 错误时释放锁
			return NTP_ERROR_RTC_SYNC;
		}

		// 获取同步后的RTC时间
		if (get_rtc_time(current_time) != 0)
		{
			printf("Failed to read RTC time\r\n");
			xSemaphoreGive(xMutex); // 错误时释放锁
			return NTP_ERROR_RTC_SYNC;
		}

		printf(
				"NTP Sync: Time synced. Current time: %04d-%02d-%02d %02d:%02d:%02d\r\n",
				current_time->tm_year, current_time->tm_mon,
				current_time->tm_mday, current_time->tm_hour,
				current_time->tm_min, current_time->tm_sec);

		xSemaphoreGive(xMutex); // 成功时释放锁
		return NTP_SUCCESS;
	}
	else
	{
		printf("Failed to take mutex for NTP sync.\r\n");
		return NTP_ERROR_RTC_SYNC; // 获取锁失败
	}
}

//NTP初始化+连接WiFi
int32_t ntp_init_and_connect(SemaphoreHandle_t xMutex)
{
	// 尝试获取互斥锁，保护UART通信
	if (xSemaphoreTake(xMutex, portMAX_DELAY) == pdTRUE)
	{
		if (ntp_init() != NTP_SUCCESS)
		{
			printf("NTP init failed.\r\n");
			xSemaphoreGive(xMutex); // 错误时释放锁
			return NTP_ERROR_WIFI_CONNECT;
		}

		if (ntp_wifi_connect(WIFI_SSID, WIFI_PASSWORD) != NTP_SUCCESS)
		{
			printf("WiFi connect failed.\r\n");
			xSemaphoreGive(xMutex); // 错误时释放锁
			return NTP_ERROR_WIFI_CONNECT;
		}

		printf("NTP client initialized and WiFi connected successfully.\r\n");
		xSemaphoreGive(xMutex); // 成功时释放锁
		return NTP_SUCCESS;
	}
	else
	{
		printf("Failed to take UartMutex during NTP init.\r\n");
		return NTP_ERROR_WIFI_CONNECT; // 获取锁失败
	}
}

